<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form v-show="isShow" :inline="true" :model="listQuery" class="form-container">
        <el-row>
          <el-col :span="5">
            <el-form-item label-width="50px" label="客户:" class="postInfo-container-item">
              <el-select v-model="listQuery.customerName" :remote-method="getRemoteUserList" filterable default-first-option remote clearable placeholder="客户搜索" style="width: 180px" @change="customerFilter">
                <el-option v-for="(item,index) in userListOptions" :key="item+index" :label="item.customerName" :value="item.customerId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label-width="50px" label="品名:" class="postInfo-container-item">
              <el-input v-model="listQuery.goodsName" placeholder="品名搜索" style="width: 180px;" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="50px" label="类别:" class="postInfo-container-item">
              <el-input v-model="listQuery.cateName" placeholder="类别搜索" style="width: 150px;" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label-width="100px" label="开始时间:" class="postInfo-container-item">
              <el-date-picker v-model="startTimeStr" type="date" format="yyyy-MM-dd" align="right" placeholder="开始时间" :picker-options="pickerOptions" style="width: 150px" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label-width="100px" label="结束时间:" class="postInfo-container-item">
              <el-date-picker v-model="endTimeStr" type="date" format="yyyy-MM-dd" align="right" placeholder="结束时间" :picker-options="pickerOptions" style="width: 150px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
              确定生成
            </el-button>
            <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-document" @click="handleDownload">
              导出 Excel
            </el-button>
          </el-col>
        </el-row>

      </el-form>

      <div class="demo-block-control" style="left: 0px;" @click="handleShowHide">
        <div v-if="isShow"> <i class="el-icon-caret-top" />
          <span>隐藏搜索</span></div>
        <div v-else> <i class="el-icon-caret-bottom" />
          <span>显示搜索</span></div>
      </div>

    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      show-summary
      :summary-method="getSum"
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column prop="customerName" label="客户" align="left" width="120" show-overflow-tooltip sortable />
      <el-table-column prop="goodsName" label="商品名称" align="left" show-overflow-tooltip sortable />
      <el-table-column prop="cateName" label="商品分类" align="left" width="120" show-overflow-tooltip sortable />
      <el-table-column prop="receivableQuantity" label="可领取数" align="center" width="120" sortable />
      <el-table-column prop="receivedQuantity" label="已领取数" align="center" width="120" sortable />
      <el-table-column prop="totalQuantity" label="总投放数" align="center" width="120" />
      <el-table-column prop="receivePrice" label="领取押金" align="center" width="120" />
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="getList" />
  </div>
</template>

<script>
// import { goodsList } from '@/api/village'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { formatStr2Time, parseTime } from '@/utils/index'
import { searchUser } from '@/api/remote-search'
import { gift } from '@/api/store'

export default {
  name: 'MultiReport',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      downloadLoading: false,
      isShow: true,
      userListOptions: [],
      startTimeStr: '',
      endTimeStr: '',
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        startTime: 0,
        endTime: 0,
        customerName: '',
        customerId: 0,
        goodsName: '',
        giftNum: 0,
        cateName: ''
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      }
    }
  },
  created() {
    // this.getList()
  },
  methods: {
    getList() {
      this.listQuery.startTime = 0
      this.listQuery.endTime = 0
      if (this.startTimeStr !== '') {
        this.listQuery.startTime = formatStr2Time(this.startTimeStr)
      }
      if (this.endTimeStr !== '') {
        this.listQuery.endTime = formatStr2Time(this.endTimeStr) + 86399
        if (this.listQuery.endTime < this.listQuery.startTime) {
          this.$message({
            type: 'warning',
            message: '开始时间不能大于结束时间'
          })
          return
        }
      }
      // console.log(this.listQuery)
      this.listLoading = true
      const filterParam = { filterParam: this.listQuery, timeMode: '' }
      gift(this.listQuery, filterParam).then(response => {
        // this.list = response.data.items
        this.total = response.data.total
        var items = response.data.items
        for (var i = 0; i < items.length; i++) {
          items[i].receivePrice = items[i].receivePrice.toFixed(2)
        }
        this.list = items
        // console.log(response)
        // Just to simulate the time of the request
        this.listLoading = false
      },
      error => {
        console.log(error)
        this.listLoading = false
      })
    },
    getRemoteUserList(query) {
      searchUser(query).then(response => {
        if (!response.data.items) return
        this.userListOptions = response.data.items.map(v => {
          const uItem = { customerId: v.userId, customerName: v.termName }
          return uItem
        })
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleShowHide() {
      this.isShow = !this.isShow
    },
    customerFilter(e) {
      console.log(e)
      this.listQuery.customerId = e
    },
    handleDownload() {
      this.downloadLoading = true
      const filename = '赠品导出' + parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['客户', '商品名称', '商品分类', '可领取数', '已领取数', '总投放数', '领取押金']
        const filterVal = ['customerName', 'goodsName', 'cateName', 'receivableQuantity', 'receivedQuantity', 'totalQuantity', 'receivePrice']
        const list = this.list
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: filename,
          autoWidth: true,
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSum(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (data == null || data === undefined) { return }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = sums[index].toFixed(2)// += ' 元'
        } else {
          sums[index] = ''
        }
      })

      return sums
    }
  }
}
</script>
<style scoped>
.el-form--inline .el-form-item {
  display: inline-block;
  margin-right: 5px;
  vertical-align: top;
}
.el-form-item {
  margin-bottom: 10px;
}
.demo-block-control {
  height: 40px;
  box-sizing: border-box;
  background-color: #fff;
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
  text-align: center;
  margin-top: -1px;
  cursor: pointer;
  position: relative;
}
</style>
